package com.daocao.hua.view;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;

import com.daocao.hua.event.HomeBtnTouchEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by xsooy-pc on 18-9-4.
 */

public class HomeFloatTouchTwoListener implements View.OnTouchListener {
    private Context context;
    int lastX, lastY;
    int firstX, firstY;
    public HomeFloatTouchTwoListener(Context context) {
        this.context = context;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int ea = event.getAction();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
//            int screenHeight = dm.heightPixels - 100;//需要减掉图片的高度
        int screenHeight = dm.heightPixels;//需要减掉图片的高度
        switch (ea) {
            case MotionEvent.ACTION_DOWN:
                firstX = (int) event.getRawX();
                firstY = (int) event.getRawY();
                lastX = (int) event.getRawX();//获取触摸事件触摸位置的原始X坐标
                lastY = (int) event.getRawY();
            case MotionEvent.ACTION_MOVE:
                //event.getRawX();获得移动的位置
                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY;
                int l = v.getLeft() + dx;
                int b = v.getBottom() + dy;
                int r = v.getRight() + dx;
                int t = v.getTop() + dy;

                //下面判断移动是否超出屏幕
                if (l < 0) {
                    l = 0;
                    r = l + v.getWidth();
                }
                if (t < 0) {
                    t = 0;
                    b = t + v.getHeight();
                }
                if (r > screenWidth) {
                    r = screenWidth;
                    l = r - v.getWidth();
                }
                if (b > screenHeight) {
                    b = screenHeight;
                    t = b - v.getHeight();
                }
                v.layout(l, t, r, b);

                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                v.postInvalidate();
                break;
            case MotionEvent.ACTION_UP:
                if (((firstX - 5) <= (int) event.getRawX() && (int) event.getRawX() <= (firstX + 5))
                        && ((int) event.getRawY() >= (firstY - 5) && (int) event.getRawY() <= (firstY + 5))) {
//                    EventBus.getDefault().post(new HomeBtnTouchEvent());
                }
                break;
        }
        return true;
    }
}

